//
//  VOLCommentViewController.m
//  Volver
//
//  Created by administrator on 14-10-20.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLCommentViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "REFrostedViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"

#import "VOLAppDelegate.h"
#import "VOLMyJourneyViewController.h"

@interface VOLCommentViewController ()
{
    VOLAppDelegate *del;
    JSONDecoder *jd;
    MBProgressHUD *HUD;
    
    //两个变量用来接收评论和打分
    NSString *content;
    int score;
    
    //用来记录评论是否上传成功的标志
    BOOL isCommentSubmit;
}
@end

@implementation VOLCommentViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //初始化一些对象
    del = kGetDel;
    jd = [[JSONDecoder alloc] init];
    isCommentSubmit = NO;
    
    //添加标题
    self.title = @"订单评价";
    
    //添加返回按钮
    addBackButton();
    
    //设置textView上的提示信息
    self.contentTextView.text = @"请输入100字以内的评论";
    self.contentTextView.textColor = kPriceLabelColor;
    //设置代理
    self.contentTextView.delegate = self;
    
    //添加“提交”按钮
    UIButton *submitBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kViewHeight - 44, kViewWidth, 44)];
    submitBtn.backgroundColor = [UIColor colorWithRed:1 green:90.0/255 blue:95.0/255 alpha:0.9];
    [submitBtn addTarget:self action:@selector(submitComment:) forControlEvents:UIControlEventTouchUpInside];
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    
    [self.view addSubview:submitBtn];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 按钮点击事件
#pragma mark 点击星星打分
- (IBAction)gradeHouse:(UIButton *)sender {
    for (int i = 1; i <= 5; i++) {
        if (i <= sender.tag) {
            UIButton *button = (UIButton *)[self.view viewWithTag:i];
            [button setBackgroundImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateNormal];
        }else{
            UIButton *button = (UIButton *)[self.view viewWithTag:i];
            [button setBackgroundImage:[UIImage imageNamed:@"nullstar.png"] forState:UIControlStateNormal];
        }
    }
    //记录下打分
    score = sender.tag;
}

#pragma mark 返回事件
-(void)goBack:(id)sender{
    back;
}

#pragma mark Done按钮事件
-(void)dismissKeyBoard:(id)sender{
    [self.view endEditing:YES];
}

#pragma mark 提交评论
-(void)submitComment:(id)sender{
    content = self.contentTextView.text;
    NSString *alertMessage;
    if ([content isEqualToString:@"请输入100字以内的评论"]) {
        if (score == 0) {
            alertMessage = @"请给房屋评价并打分";
        }else{
            alertMessage = @"请给房屋评价";
        }
    }else{
        if (score == 0) {
            alertMessage = @"请给房屋打分";
        }
    }
    
    if (alertMessage != nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:alertMessage delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }

    
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    [HUD showAnimated:YES whileExecutingBlock:^{
        NSLog(@"提交评价");
        //调用提交方法，提交评价和分数
        [self submitCommentData];
    } completionBlock:^{
        [HUD removeFromSuperview];
        HUD = nil;
        
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        if (isCommentSubmit) {
            HUD.labelText = @"提交成功";
            HUD.mode = MBProgressHUDModeCustomView;
            HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Checkmark.png"]];
        }
        else{
            HUD.labelText = @"提交失败";
            HUD.mode = MBProgressHUDModeText;
        }
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
            
            if (self.sourceFrom == 25) {//返回“我的旅程”，同时刷新
                del.isRefresh = 6;
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
            }
            if (self.sourceFrom == 26) {//返回“历史”，同时刷新
                del.isRefresh = 7;
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
            }
            
            
        }];
    }];
    
}

#pragma mark - 连网操作
#pragma mark 提交数据
-(void)submitCommentData{
    NSString *urlstr = [NSString stringWithFormat:@"%@comment/addComment",kHTTPHome];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setPostValue:[NSString stringWithFormat:@"%d",self.houseID] forKey:@"houseID"];
    [request setPostValue:[NSString stringWithFormat:@"%d",del.currentUser.userID] forKey:@"userID"];
    [request setPostValue:content forKey:@"content"];
    [request setPostValue:[NSString stringWithFormat:@"%d",score] forKey:@"score"];
    [request setPostValue:[NSString stringWithFormat:@"%f",kGetCurrentTime] forKey:@"commentTime"];
    
    //设置代理
    request.delegate = self;
    [request startAsynchronous];

}

#pragma mark - 代理方法
#pragma mark - TextView代理
#pragma mark 当开始输入时判断是否清空
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"请输入100字以内的评论"]) {
        textView.text = @"";
        textView.textColor = kBlackColor;
    }
    //添加Done按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(dismissKeyBoard:)];
    self.navigationItem.rightBarButtonItem.tintColor = kThemeColor;
    return YES;
}
#pragma mark 输入结束时是否还原提示文字
-(BOOL)textViewShouldEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        self.contentTextView.text = @"请输入100字以内的评论";
        self.contentTextView.textColor = kPriceLabelColor;
    }
    
    self.navigationItem.rightBarButtonItem = nil;
    return YES;
}
#pragma mark 编辑过程中检查是否超出范围
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (range.location >= 100) {
        return NO;
    }
    
    return YES;
}

#pragma mark - 异步请求代理方法
#pragma mark 请求成功
-(void)requestFinished:(ASIFormDataRequest *)request{
    NSData *data = [request responseData];
    if (data == nil) {
        NSLog(@"submitCommentData---data为空");
        return;
    }
    NSDictionary *dic = [jd objectWithData:data];
    int result = [[dic objectForKey:@"status"] intValue];
    if (result) {
        NSLog(@"上传成功");
        isCommentSubmit = YES;
    }else{
        NSLog(@"上传失败");
    }
}

#pragma mark 请求失败
-(void)requestFailed:(ASIFormDataRequest *)request{
    NSLog(@"submitCommentData------请求失败");
}

@end





